<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @open="dialogOpen" @close="closeDialog">
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="roleIds" v-loading="loading">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="clickSubmit">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </template>
  </el-dialog>
</template>
<script>
import { reqGetUserInfoById } from '@/api/user'
import { reqGetRoleList } from '@/api/setting'
import { reqAssignRoles } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      list: [],
      roleIds: [],
      loading: false
    }
  },
  created() {
  },
  methods: {
    closeDialog() {
      // 传给父组件，让父组件来控制显示或者隐藏
      this.$emit('update:showRoleDialog', false)
    },
    // 发送获取角色列表
    async getRoleList() {
      const { data } = await reqGetRoleList(1, 100)
      this.list = data.rows
      return this.list
    },
    // 获取用户的当前角色，进行回显
    async getUserInfoById() {
      const { data } = await reqGetUserInfoById(this.userId)
      this.roleIds = data.roleIds
      return this.roleIds
    },
    // 每次打开后调用事件openDialog
    dialogOpen() {
      this.loading = true
      // this.getRoleList()
      // this.getUserInfoById()
      Promise.all([this.getRoleList(), this.getUserInfoById()]).then(res => {
        console.log(res)
        this.loading = false
      })
    },
    // 点击后给员工分配角色
    async clickSubmit() {
      await reqAssignRoles({
        id: this.userId,
        roleIds: this.roleIds
      })
      this.$message.success('更新员工权限成功')
      // this.getRoleList()
      // 关闭弹框
      this.closeDialog()
    }
  }
}
</script>
<style lang="scss" scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
